<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          :content="currentStepName"
          @back="handleBack"
        >
        </el-page-header>

        <div class="card-box--downloadbtn">
          <el-tooltip effect="dark" content="预览" placement="bottom">
            <template #default>
              <el-button
                circle
                type="primary"
                icon="el-icon-view"
                @click="handleView"
              ></el-button>
            </template>
          </el-tooltip>
          <el-tooltip effect="dark" content="下载" placement="bottom">
            <template #default>
              <el-button
                type="primary"
                circle
                icon="el-icon-download"
                @click="handleDownload"
              ></el-button>
            </template>
          </el-tooltip>

          <el-button v-if="canRecall" type="primary" @click="handleRecall"
            >撤 回</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>基础信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <basic-info :basicInfoData="basicInfoData" v-show="show1" />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>验收记录</span>

          <div v-if="show2" @click="show2 = !show2" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show2 = !show2" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <record-info :recordInfoData="recordInfoData" v-show="show2" />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>审批记录</span>

          <div v-if="show6" @click="show6 = !show6" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show6 = !show6" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <approval-info :approveRecord="approveRecord" v-show="show6" />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流程状态</span>

          <div v-if="show3" @click="show3 = !show3" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show3 = !show3" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <status-info
          :currentStep="currentStep"
          :steps="isStep ? steps : steps2"
          :isChargehand="isChargehand"
          v-show="show3"
        />
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box" v-if="isHandler === IsHandlerEnum.EDIT">
      <!-- <el-card class="card-box"> -->
      <template #header>
        <div class="card-box-header">
          <span>待处理</span>

          <div v-if="show4" @click="show4 = !show4" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show4 = !show4" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <!-- 有监理流程 -->
      <template v-if="isStep">
        <el-collapse-transition>
          <div v-show="show4">
            <component
              :is="steps[currentStep].step"
              :key="currentStep"
              :recordId="recordId"
              :taskId="taskId"
              :storageData="storageData"
              :projectTeam="projectTeam"
            ></component>
          </div>
        </el-collapse-transition>
      </template>
      <!-- 无监理流程 -->
      <template v-else>
        <el-collapse-transition>
          <div v-show="show4">
            <component
              :is="steps2[currentStep].step"
              :key="currentStep"
              :recordId="recordId"
              :taskId="taskId"
              :storageData="storageData"
              :projectTeam="projectTeam"
            ></component>
          </div>
        </el-collapse-transition>
      </template>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>流转记录</span>

          <div v-if="show5" @click="show5 = !show5" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show5 = !show5" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="show5">
          <flow-info />
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ProcessStatusEnum, IsHandlerEnum } from "../types";
import { getFlowInfo, postRecall, getProTeamMembers } from "/@/api/acceptance";
import StatusInfo from "../components/processInfo/StatusInfo.vue";
import BasicInfo from "../components/processInfo/BasicInfo.vue";
import RecordInfo from "../components/processInfo/RecordInfo.vue";
import FlowInfo from "../components/processInfo/FlowInfo.vue";
import ApprovalInfo from "../components/processInfo/ApprovalInfo.vue";
import { downloadpdf, viewpdf } from "/@/utils/download";
import NotifMessage from "/@/utils/message/notification";

// 批量导入组件
const modules = import.meta.globEager("../components/steps/*.vue");
const modules2 = import.meta.globEager("../components/steps2/*.vue");
const router = useRouter();
const route = useRoute();
let currentStep = ref(ProcessStatusEnum.ACT_010);
let currentStepName = ref("");
let steps = ref([]);
let steps2 = ref([]);
let recordId = ref(""); // 最后一次的验收记录ID
let basicInfoData = ref<object>({}); // 基础信息
let recordInfoData = ref<Array<any>>([]); // 验收记录
let storageData = ref<object>({}); // 流程发起的数据存储
let isHandler = ref<number>(IsHandlerEnum.NO_EDIT); // 0 不可编辑   1 可编辑
let canRecall = ref<number>(0);
let taskId = ref("");
let cacheBillName = ref(""); // 下载pdf使用的名称
let show1 = ref(true);
let show2 = ref(true);
let show3 = ref(true);
let show4 = ref(true);
let show5 = ref(true);
let show6 = ref(true); // 审批记录
let projectTeam = ref([]);
let isStep = ref<boolean>(true);
let approveRecord = ref([]); // 审批记录信息
let isChargehand = ref(5); // 是经过副组长

// 有监理流程
const processStatus = new Map([
  [0, "发送验收申请"],
  [1, "发送验收通知"],
  [2, "监理初审"],
  [3, "确认验收方案"],
  [4, "现场验收"],
  [5, "专业组长审批"],
  [6, "副组长审批"],
  [7, "执行组长审批"],
  [8, "完成"]
]);

// 无监理流程
const processStatus2 = new Map([
  [0, "发送验收申请"],
  [1, "确认验收方案"],
  [2, "现场验收"],
  [3, "专业组长审批"],
  [4, "副组长审批"],
  [5, "执行组长审批"],
  [6, "完成"]
]);

// ----------------------------------

// TODO  进入详情页首先判断验收类型，然后再进行组件的导入显示，以及流程的分配
// 处理批量导入的组件
const modulesArray = Object.values(modules).map(v => v.default);
modulesArray.forEach((item, index) => {
  steps.value.push({ step: item, title: processStatus.get(index) });
});

// 处理批量导入的组件
const modulesArray2 = Object.values(modules2).map(v => v.default);
modulesArray2.forEach((item, index) => {
  steps2.value.push({ step: item, title: processStatus2.get(index) });
});

// ----------------------------------

// 进入详情进行判断使用哪中流程
if (route.query?.flowMinType && route.query.flowMinType === "7") {
  isStep.value = true;
  if (route.query.nodeDefId === "END") {
    currentStepName.value = "完成";
  } else {
    const stepValue = ProcessStatusEnum[route.query.nodeDefId as string];
    currentStepName.value = processStatus.get(stepValue);
  }
}
if (route.query?.flowMinType && route.query.flowMinType === "8") {
  isStep.value = false;
  if (route.query.nodeDefId === "END") {
    currentStepName.value = "完成";
  } else {
    const stepValue = ProcessStatusEnum[route.query.nodeDefId as string];
    currentStepName.value = processStatus2.get(stepValue);
  }
}

// 进入详情进行判断
if (route.query?.nodeDefId && route.query?.mode) {
  // if (route.query?.mode === "add" || !route.query?.instanceId) {
  // 涉及到表单组件的传参，所以这里尽可能为false
  if (route.query?.mode === "add") {
    isHandler.value = IsHandlerEnum.EDIT;
  }

  currentStep.value = ProcessStatusEnum[route.query.nodeDefId as string];
} else {
  router.push({ path: "/acceptance/completed", replace: true });
}
// 请求详情信息
const getDatailData = async () => {
  if (!route.query?.contractId) {
    return;
  }
  const { contractId } = route.query;
  const params = {
    id: contractId
  };
  const { code, data } = await getFlowInfo(params);
  if (code === 200) {
    /*
     * warning：
     * const { acceptanceRecordList } = data;
     * 当进行解构时，会失去响应，导致子组件不能接收到数据
     * 可使用以下方法进行解决
     * const accept = toRef(data, "acceptanceRecordList");
     */

    // 验收信息赋值
    recordInfoData.value = data?.acceptanceRecordList ?? [];
    // 审批记录
    approveRecord.value = data?.approveRecordList ?? [];
    // 验收记录ID获取赋值
    if (data.acceptanceRecordList && data.acceptanceRecordList.length) {
      const recordLength = data?.acceptanceRecordList?.length;
      recordId.value = data?.acceptanceRecordList[recordLength - 1]?.id ?? null;
    }

    // 是否显示撤回按钮
    if (data?.canRecall) {
      canRecall.value = data.canRecall;
    }
    // taskId
    taskId.value = data?.taskId ?? "";

    const {
      billName,
      billNum,
      contractName,
      contractNum,
      partyA,
      directorAName,
      partyB,
      directorBName,
      createUser,
      createUserName,
      createTime,
      // arrivalDate,
      projectName,
      projectManageId,
      directorA,
      directorBId,
      flowStartAttachmentArr,
      flowMinType
    } = data.formBaseInfo;

    basicInfoData.value = {
      billName,
      billNum,
      contractName,
      contractNum,
      partyA,
      directorAName,
      partyB,
      directorBName,
      createUser,
      createUserName,
      createTime,
      // arrivalDate,
      projectName,
      projectManageId,
      directorA,
      directorBId,
      flowStartAttachmentArr,
      flowMinType
    };

    // 获取项目组信息
    if (data.formBaseInfo.contractId) {
      getTeamMembers(data.formBaseInfo.contractId);
    }

    storageData.value = data.formBaseInfo;
    cacheBillName.value = data.formBaseInfo.billName;

    // 是否可编辑判断
    isHandler.value = data?.isHandler;

    // 判断是否跳过副组长
    if (data.formBaseInfo?.isChargehand) {
      isChargehand.value = data.formBaseInfo.isChargehand;
    }
  }
};

const getTeamMembers = async (id: string | number) => {
  try {
    const params = {
      id
    };
    const res: any = await getProTeamMembers(params);
    if (res.code === 200) {
      projectTeam.value = res.data.memberTypeList;
    }
  } catch (err) {
    console.log(err);
  }
};

// 返回按钮事件
const handleBack = () => {
  // TODO  根据来源进行处理
  if (route.query.source === "work") {
    // router.push({ path: "/work/dashboard", replace: true });
    router.go(-1);
  } else {
    router.push({ path: "/acceptance/completed", replace: true });
  }
};

// 下载事件
const handleDownload = async () => {
  if (!route.query?.contractId) {
    return;
  }
  const { contractId, flowId, instanceId } = route.query;
  const params = {
    contractInfoId: contractId,
    flowId: flowId,
    instanceId: instanceId,
    pdfName: cacheBillName.value
  };
  downloadpdf(params, "common");
};

// 预览事件
const handleView = async () => {
  if (!route.query?.contractId) {
    return;
  }
  const { contractId, flowId, instanceId } = route.query;
  const params = {
    contractInfoId: contractId,
    flowId: flowId,
    instanceId: instanceId
  };
  viewpdf(params, "common");
};

const handleRecall = async () => {
  try {
    const { instanceId, preNodeId } = route.query;
    const params = {
      instanceId,
      nodeId: preNodeId
    };
    const { code, message } = await postRecall(params);
    if (code === 200) {
      NotifMessage.success(message);
      handleBack();
    } else {
      message && NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

// if (route?.query?.mode && route?.query?.mode !== "add") {
getDatailData();
// }
</script>

<style lang="scss" scoped>
// .content {
//   :deep .el-page-header__content {
//     font-size: 16px;
//   }
//   .card-box {
//     margin-bottom: 10px;
//     &-header {
//       display: flex;
//       justify-content: space-between;
//       align-items: center;
//       .header-btn {
//         font-size: 14px;
//         cursor: pointer;
//       }
//     }
//     &--headerwrap {
//       display: flex;
//       justify-content: space-between;
//       align-items: center;
//     }
//     &--downloadbtn {
//       display: flex;
//       justify-content: flex-end;
//       align-items: center;
//       width: 140px;
//     }
//   }
//   .show-wrap {
//     margin-top: 10px;
//   }
// }
</style>
